package sfbot;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class TextFile implements LogDatabase {
	private File fileOut;
	private File fileIn;
	private FileOutputStream out;
	private FileInputStream in;
	private List<User> users;
	public TextFile(String src, String dest, List<User> users){
		this.users = users;		
		fileIn = new File(src);
		fileOut = new File(dest);
		
		try {
			in = new FileInputStream(fileIn);
			out = new FileOutputStream(dest, true);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public Map<String,List<List<LogLine>> > read(Channel channel) {
		Scanner scan = new Scanner(in);
		Map<String, List<List<LogLine>>> tagMap = new TreeMap<String, List<List<LogLine>>>();
		while(scan.hasNextLine()){
			// Create the tags
			String[] tags = scan.nextLine().split(";");
			List<LogLine> conversation = new ArrayList<LogLine>();
			while(scan.hasNextLong()){
				// Prep the LogLine
				LogLine log;
				long timestamp = scan.nextLong();			// Time (as long)
				Calendar time = Calendar.getInstance();		// Calendar (from long)
				time.setTimeInMillis(timestamp);
				String nick = scan.nextLine();				// User nick
				String msg = scan.nextLine();				// Message
				
				// Search to see if the user already exists
				User user = null;
				for(User u : users){
					if(u.equals(nick)){
						// Grab the user
						user = u;
						break;
					}
				}
				
				// Create the user if no user was found
				if(user == null){
					user = new IrcUser(nick);
					users.add(user);
				}
				
				// Add the LogLine
				conversation.add(
					new LogLine(msg, user, channel, time)
				);
			}
			for(String t : tags){
				if(tagMap.containsKey(t))
					tagMap.get(t).add(conversation);
				else{
					List<List<LogLine>> related = new ArrayList<List<LogLine>>();
					related.add(conversation);
					tagMap.put(t, related);
				}
			}
		}
		return tagMap;
	}

	@Override
	public void write(List<LogLine> logs, List<String> tags) {
		PrintWriter print = new PrintWriter(out);
		for(String s : tags)
			print.write(s + ";");
		print.println();
		for(LogLine l : logs){
			print.println(l.getTimeStamp().getTimeInMillis());
			print.println(l.getNick());
			print.println(l.getMessage());
		}
		print.close();

	}

}
